package com.bree.erp.jsf.service.wrapper;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;

import com.bree.erp.entity.PurchaseRequisition;
import com.bree.erp.entity.Status;
import com.bree.erp.service.PurchaseRequisitionService;
import com.bree.erp.service.PurchaseRequisitionWrapperService;

public class PurchaseRequisitionWrapperServiceBean implements PurchaseRequisitionWrapperService {

	private static Logger LOG = Logger.getLogger(PurchaseRequisitionWrapperServiceBean.class);
			
	private PurchaseRequisitionService service;
	private String userId;
	private Long projectId;
	private Status[] status;
	private List<PurchaseRequisition> cachedList;
	
	public PurchaseRequisitionWrapperServiceBean(PurchaseRequisitionService service, String userId, Long projectId, Status ... status) {
		this.service = service;
		this.userId = userId;
		this.projectId = projectId;
		this.status = status;
	}

	@Override
	public PurchaseRequisition read(Long id) {
		
		PurchaseRequisition template = new PurchaseRequisition();
		template.setId(id);
		
		if(cachedList == null) {
			list();
		}
		
		int idx = cachedList.indexOf(template);
		return cachedList.get(idx);
	}

	@Override
	public Collection<PurchaseRequisition> list() {
		
		if(cachedList == null) {
			cachedList = new ArrayList<PurchaseRequisition>();
			for(Status s : status) {
				Collection<PurchaseRequisition> list = service.list(userId, projectId, s);
				cachedList.addAll(list);
			}
			
			
		}
		
		LOG.debug(status + ":" + cachedList.size());
		
		return cachedList;
	}

}
